from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from app.models import User
from app.views import isLoginStatus
from learningPlanet.views import addMessage
from link.views import get_friend_links
from playingPlanet.models import Moments, JudgeForMoment


# 快乐星球
def index(request):
    if request.method == 'GET':
        LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
        # 快乐星球的链接 随机链接
        # blogObj = Blog.objects.all()
        # blogNum = blogObj.count()  # 博客数量
        # showSearchBox = 0  # 显示搜索框
        # toLearnPlanetLinkId = randint(1, blogNum + 1)
        if userId:
            userAvatar = str(User.objects.filter(id=userId).first().avatar)
            username = str(User.objects.filter(id=userId).first().username)

        # 返回动态的数据
        momentsNum = Moments.objects.filter(isShow=1).filter(Q(userId_id=userId) | Q(ispublic=1)).count()
        momentObjs = Moments.objects.filter(isShow=1).filter(Q(userId_id=userId) | Q(ispublic=1))[
                     momentsNum - 5:momentsNum]  # 显示我自己的 和别人公开的
        momentList = returnMomentList(momentObjs)
        momentList.reverse()
        momentList = momentList  # 仅取最新的5条动态

        link_list = get_friend_links()
        return render(request, 'playingplanet.html', context=locals())


# 返回动态的数据
def returnMomentList(momentObjs):
    momentList = []
    for momentObj in momentObjs:
        imgList = [
            str(momentObj.img1),
            str(momentObj.img2),
            str(momentObj.img3),
            str(momentObj.img4),
            str(momentObj.img5),
            str(momentObj.img6),
            str(momentObj.img7),
            str(momentObj.img8),
            str(momentObj.img9)
        ]
        video = str(momentObj.video)

        # 获取评论的数据
        judgeList = []
        judgeObjs = JudgeForMoment.objects.filter(moment_id=momentObj.id)
        for judgeObj in judgeObjs:
            judgeConDic = {
                'juderId': judgeObj.judger.id,
                'juderName': judgeObj.judger.username,
                'content': judgeObj.content,
            }
            judgeList.append(judgeConDic)

        conDic = {
            'id': momentObj.id,
            'userId': str(momentObj.userId_id),
            'userAvatar': str(momentObj.userId.avatar),
            'username': momentObj.userId.username,
            'date': str(momentObj.date).split('.')[0],
            'content': momentObj.content,
            'imgList': imgList,
            'video': video,
            'callNum': momentObj.callNum,
            'judgeList': judgeList
        }
        momentList.append(conDic)
    return momentList


# 异步加载动态
def addmoment(request):
    if request.method == 'POST':
        num = int(request.POST.get('num'))  # 请求的次数
        userId = request.POST.get('userId')
        userId = userId if userId != 'None' else 0
        momentsNum = Moments.objects.filter(isShow=1).filter(Q(userId_id=userId) | Q(ispublic=1)).count()
        start = momentsNum - 5 * (num + 1)
        end = momentsNum - 5 * num

        start = start if start >= 0 else 0
        end = end if end >= 0 else 0

        if start == end:  # 如果两个相等都等于0 说明所有数据已经加载完
            return JsonResponse({'momentList': []})

        # 加载自己的和公开的动态
        momentObjs = Moments.objects.filter(isShow=1).filter(Q(userId_id=userId) | Q(ispublic=1))[start:end]
        momentList = returnMomentList(momentObjs)
        momentList.reverse()

        return JsonResponse({'momentList': momentList})


# 接受快乐星球发布的动态
def recFromPlaying(request):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:
        redirect(reverse('app:index'))
    if request.method == 'POST':
        userId = request.POST.get('userId')
        content = request.POST.get('content')

        public = request.POST.get('public')
        public = 1 if public == 'on' else 0
        imgList = []
        isHaveImg = ''
        for i in range(1, 10):
            imgList.append(request.FILES.get(f'img{i}'))
            if request.FILES.get(f'img{i}'):
                isHaveImg = 1
        video = request.FILES.get('video') if not isHaveImg else ''

        save_success = Moments.save_obj(userId, content, public, imgList, video)
        if not save_success: return JsonResponse({'msg': '动态发布失败。'})

    return redirect(reverse('playingPlanet:index'))


# 点赞
def CallNum(request):
    if request.method == 'POST':
        try:
            momentId = request.POST.get('id')
            docall = request.POST.get('call')
            momentObj = Moments.objects.filter(id=momentId).first()
            nowLikes = momentObj.callNum
            momentObj.callNum = nowLikes + int(docall)
            momentObj.save()

            if int(docall) > 0:
                senderId = request.POST.get('userId')
                receiverId = momentObj.userId_id
                content = 'ta点赞了你的动态。'
                addMessage(senderId, receiverId, content)
            return JsonResponse({'msg': '点赞成功!'})
        except:
            return JsonResponse({'msg': '点赞失败!'})


# 删除动态
def deletemoment(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        userId = request.POST.get('userId')
        momentObj = Moments.objects.filter(Q(id=id) & Q(userId=userId)).first()
        if momentObj:
            momentObj.isShow = 0
            momentObj.save()
            return JsonResponse({'msg': '删除成功!'})
        return JsonResponse({'msg': '删除失败!'})


# 评论动态
def pinlunmoment(request):
    if request.method == 'POST':
        content = request.POST.get('content')
        judgerId = request.POST.get('judgerId')
        momentId = request.POST.get('momentId')

        JudgeForMomentObj = JudgeForMoment()
        JudgeForMomentObj.content = content
        JudgeForMomentObj.judger_id = judgerId
        JudgeForMomentObj.moment_id = momentId
        JudgeForMomentObj.save()

        return JsonResponse({'msg': '评论成功!'})

    return JsonResponse({'msg': '失败!'})
